//---------------------------------------------------------------------
// File: splusvc.cs
// 
// Summary: Service Implementation File
//
//---------------------------------------------------------------------
// Sharepoint Updater
//---------------------------------------------------------------------

namespace splusvc
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.ServiceProcess;
    using System.Text;
    using System.IO;
    using CodePlex.EnterpriseFramework;

    public enum ServicesStatus {Started, Stopped};

    public partial class splusvc : ServiceBase
    {
        private FileSystemWatcher watcher;
        private ServicesStatus servicesStatus;

        public splusvc()
        {
            InitializeComponent();
            servicesStatus = ServicesStatus.Stopped;
        }

        protected override void OnStart(string[] args)
        {
            // Configure Folder Watcher
            watcher = new System.IO.FileSystemWatcher();            
            watcher.Path = ConfigurationManager.WatchingFolder;
            watcher.Filter = "*.xml";
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.EnableRaisingEvents = true;
            watcher.IncludeSubdirectories = false;
            // Add Events
            watcher.Created += new FileSystemEventHandler(OnFileChanged);
            watcher.Renamed += new RenamedEventHandler(OnFileChanged);
            // Set Service Status
            servicesStatus = ServicesStatus.Started;
            // Process files if found
            ProcessFiles();
        }

        protected override void OnStop()
        {
            servicesStatus = ServicesStatus.Stopped;
            base.OnStop();
        }

        protected override void OnPause()
        {
            servicesStatus = ServicesStatus.Stopped;
            base.OnPause();
        }

        protected override void OnContinue()
        {
            servicesStatus = ServicesStatus.Started;
            base.OnContinue();
            ProcessFiles();
        }

        protected override void OnShutdown()
        {
            servicesStatus = ServicesStatus.Stopped;
            base.OnShutdown();
        }

        private void OnFileChanged(object sender, System.IO.FileSystemEventArgs e)
        {
            ProcessFiles();
        }


        private void ProcessFiles()
        {
            // Check if service status is running
            if (servicesStatus == ServicesStatus.Started)
            {
                // Don't relay on event (e) file name, get all the list to initiate the old files 
                // incase if the service started after creating the files in the system folder.
                foreach (string filePath in Directory.GetFiles(ConfigurationManager.WatchingFolder))
                {
                    // Check file extension
                    if (filePath.Substring(filePath.Length - 3, 3).ToLower() == "xml")
                    {
                        // Sharepoint ListUpdaer 
                        try
                        {
                            SharepointHelper.ProcessUpdateList(filePath);
                        }
                        catch (Exception ex)
                        {
                            // Archive Failures
                            if (File.Exists(filePath))
                            {
                                try
                                {
                                    string filename = filePath.Substring(filePath.LastIndexOf("\\") + 1, filePath.Length - filePath.LastIndexOf("\\") - 1);
                                    if (!File.Exists(ConfigurationManager.ArchiveFolder + "Failures\\" + filename))
                                    {
                                        File.Move(filePath, ConfigurationManager.ArchiveFolder + "Failures\\" + filename);
                                    }
                                    else
                                    {
                                        File.Move(filePath, ConfigurationManager.ArchiveFolder + "Failures\\" + Guid.NewGuid() + ".xml");
                                    }
                                }
                                catch(Exception e)
                                {
                                    // Log Failure
                                    System.Diagnostics.EventLog.WriteEntry("splusvc", e.Message, EventLogEntryType.Error, 0, 0, System.Text.ASCIIEncoding.UTF8.GetBytes(e.ToString()));
                                }
                            }
                            // Log Failure
                            System.Diagnostics.EventLog.WriteEntry("splusvc", ex.Message, EventLogEntryType.Error, 0, 0, System.Text.ASCIIEncoding.UTF8.GetBytes(ex.ToString()));
                        }
                    }
                }
            }
        }
    }
}
